#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <unistd.h> 
#include <pthread.h> 
#include <arpa/inet.h>
#include <signal.h>

#include "process.h"
#include "network.h"
#include "database.h"
	

int sockfd;


void *start (void *ptr) {

	struct ip_and_socket new_ip_and_socket = *(struct ip_and_socket *) ptr;
	process_request (new_ip_and_socket);
	return NULL;
}

void signalHandler () {
	close (sockfd);
	exit (0);
}

int main (int argc, char *argv[]) {

	// INIT DATABASE
	pthread_mutex_init (&m_db, NULL);
	db = create_database();	

	// INIT DAEMON
	if (argc < 2)
		error ("ERROR : ./server PORT");
		
	sockfd = create_tcp_socket (atoi(argv[1]));
	listen (sockfd, 1);

    printf("\033[31mStarting peer-to-peer server on address 127.0.0.1 port %s\033[39m\n\n", argv[1]);

	// INTERRUPTION SIGNAL
	signal (SIGINT, signalHandler);
	signal (SIGQUIT, signalHandler);
	signal (SIGSEGV, signalHandler);
	
	// WAITING FOR CLIENT
	do {
		struct ip_and_socket new_ip_and_sockfd = accept_client (sockfd);
		pthread_t *thread = malloc(sizeof(pthread_t));
		pthread_create(thread, NULL, start, (void *)&new_ip_and_sockfd);
	} while (1);

	return EXIT_SUCCESS;
}
